﻿using CommonConfig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using WXEntity;

namespace CommonConfig
{
    public class RequestServer
    {
        public string WXPost(string serviceCode, Dictionary<string, string> keyValuePairs)
        {
            LogHelper.Debug(serviceCode);
          
            string json = "";
            try
            {
                // 请求参数
                RequestEntity requestEntity = new RequestEntity();
                requestEntity.ServiceCode = serviceCode;
                requestEntity.RequestParam = keyValuePairs;
                LogHelper.Debug(Newtonsoft.Json.JsonConvert.SerializeObject(requestEntity));
                // 获取配置信息
                ServerEntity serverEntity = new ServerEntity(serviceCode);
                //加载程序集(dll文件地址)，使用Assembly类   
                string dllPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory+"bin", serverEntity.Assembly + ".dll");
                Assembly assembly = Assembly.LoadFile(dllPath);

                ////获取类型，参数（名称空间+类）   
                Type type = assembly.GetType(serverEntity.NameSpaceClassName);

                ////创建该对象的实例，object类型，参数（名称空间+类）   
                object instance = assembly.CreateInstance(serverEntity.NameSpaceClassName);

                ////设置被调用方法中的参数类型，Type[]类型；如有多个参数可以追加多个   
                Type[] params_type = new Type[1];
                params_type[0] = typeof(RequestEntity);
                ////设置被调用方法中的参数值；如有多个参数可以追加多个   
                RequestEntity[] params_obj = new RequestEntity[1];
                params_obj[0] = requestEntity;

                ////执行Show_Str方法   
                object value = type.GetMethod(serverEntity.Method, params_type).Invoke(instance, params_obj);

                ResultEntity resultEntity = value as ResultEntity;
                json = Newtonsoft.Json.JsonConvert.SerializeObject(resultEntity);

            }
            catch (Exception ex)
            {
                LogHelper.Debug(serviceCode+"：" );
                LogHelper.Debug(ex);
                // 请求参数
                ResultEntity resultEntity = new ResultEntity();
                resultEntity.Code = ErrorCode.RequestFail;
                resultEntity.Msg = ex.Message;
                json = Newtonsoft.Json.JsonConvert.SerializeObject(resultEntity);
            }
            return json;
        }

        
    }
}